package cn.apestar.common.pay.wx;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jodd.http.HttpBrowser;
import jodd.http.HttpRequest;

import org.jdom2.JDOMException;
import cn.apestar.common.pay.wx.config.WxPayConfig;
import cn.apestar.common.pay.wx.util.MD5;
import cn.apestar.common.pay.wx.util.Sha1Util;
import cn.apestar.common.pay.wx.util.XMLUtil;

/*
 '微信支付服务器签名支付请求请求类
 '============================================================================
 'api说明：
 'init(app_id, app_secret, partner_key, app_key);
 '初始化函数，默认给一些参数赋值，如cmdno,date等。
 'setKey(key_)'设置商户密钥
 'getLasterrCode(),获取最后错误号
 'GetToken();获取Token
 'getTokenReal();Token过期后实时获取Token
 'createMd5Sign(signParams);生成Md5签名
 'genPackage(packageParams);获取package包
 'createSHA1Sign(signParams);创建签名SHA1
 'sendPrepay(packageParams);提交预支付
 'getDebugInfo(),获取debug信息
 '============================================================================
 '*/
@SuppressWarnings({"rawtypes","unused"})
public class RequestHandler {

	/** 统一下单url地址 */
	private String unifiedorderUrl;
	/** 商户参数 */
	private String appid;
	private String appkey;
	private String partner;
	/** Token */
	private String Token;
	private HttpRequest readFrom;

	/**
	 * 初始构造函数。
	 * 
	 * @return
	 */
	public RequestHandler(HttpServletRequest request,
			HttpServletResponse response) {
		this.Token = "token_";

		unifiedorderUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
	}

	/**
	 * 初始化函数。
	 */
	public void init(String app_id, String app_key, String partner) {
		this.appkey = app_key;
		this.appid = app_id;
		this.partner = partner;
	}

	public void init() {

	}
	
	public String genAppSign(SortedMap<String, String> params) {
		StringBuilder sb = new StringBuilder();
		Set es = params.entrySet();
		Iterator it = es.iterator();
		while(it.hasNext()){
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			
			sb.append(k);
			sb.append('=');
			sb.append(v);
			sb.append('&');
		}
		sb.append("key=");
		sb.append(this.appkey);

		String appSign = MD5.getMessageDigest(sb.toString().getBytes());
		System.out.println("appSign="+appSign);
		return appSign;
	}
	
	public String genPackageSign(SortedMap<String, String> params) {
		StringBuilder sb = new StringBuilder();
		
		Set es = params.entrySet();
		Iterator it = es.iterator();
		while(it.hasNext()){
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			
			sb.append(k);
			sb.append('=');
			sb.append(v);
			sb.append('&');
		}
		sb.append("key=");
		sb.append(this.appkey);
		

		String packageSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
		System.out.println("packageSign="+packageSign);
		return packageSign;
	}
	
	private String toXml(SortedMap<String, String> params) {
		StringBuilder sb = new StringBuilder();
		sb.append("<xml>");
		Set es = params.entrySet();
		Iterator it = es.iterator();
		while(it.hasNext()){
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			
			if ("body".equalsIgnoreCase(k)) {
				sb.append("<"+k+">");
				sb.append("<![CDATA[");
				sb.append(v);
				sb.append("]]>");
				sb.append("</"+k+">");
			} else {
				sb.append("<"+k+">");
				sb.append(v);
				sb.append("</"+k+">");
			}
		}
		
		sb.append("</xml>");

		return sb.toString();
	}
	
	public String genProductArgs(String body,
			String out_trade_no,
			String spbill_create_ip,
			String total_fee,
			String nonceStr) {

		try {
			SortedMap<String,String> packageParams = new TreeMap<String, String>();
			packageParams.put("appid", this.appid);
			packageParams.put("body", body);
			packageParams.put("mch_id", this.partner);
			packageParams.put("nonce_str", Sha1Util.getNonceStr());
			packageParams.put("notify_url", WxPayConfig.NOTIFY_URL);
			packageParams.put("out_trade_no", out_trade_no);
			packageParams.put("spbill_create_ip", spbill_create_ip);
			packageParams.put("total_fee", total_fee);
			packageParams.put("trade_type", "APP");

			String sign = genPackageSign(packageParams);
			packageParams.put("sign", sign);


		   String xmlstring =toXml(packageParams);

			return xmlstring;

		} catch (Exception e) {
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	public Map<String, String> unifiedorder(String entity) throws Exception {
		HttpBrowser browser = new HttpBrowser();
		HttpRequest httpRequest = HttpRequest.post(unifiedorderUrl);
		httpRequest.header("Content-Type", "text/xml");
		httpRequest.body(new String(entity.getBytes(), "iso-8859-1"));
		browser.sendRequest(httpRequest);
		Map<String, String> map = null;
		try {
			String resContent = browser.getPage();
			map = XMLUtil.doXMLParse(resContent );
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return map;

	}


}
